package org.softmed.rest.server.core.restlet;

import java.util.List;

import org.softmed.rest.config.Application;
import org.softmed.rest.config.Module;
import org.softmed.rest.config.Resource;

public class ResourceSetup {

	RESTServer server;
	String contextName;

	public void setupApp(Application app) {
		if (app.isActive())
			setupModules(app);
	}

	private void setupModules(Application app) {
		List<Module> mods = app.getModules();
		for (Module module : mods) {
			if (module.isActive())
				setupModule(app, module);
		}

	}

	private void setupModule(Application app, Module module) {
		List<Resource> rez = module.getResources();
		for (Resource resource : rez) {
			if (resource.isActive() && resource.getTargetUri() != null
					&& resource.getTargetUri().length() > 0) {
				setupResource(app, module, resource);
			}

		}

	}

	public void setupResource(Application app, Module module, Resource resource) {
		if (resource.getTargetUri() == null
				|| resource.getTargetUri().length() == 0)
			return;

		// String uri = resource.getTargetUri();

		String uri = "";

		if (app != null)
			if (app.getRelativeUri() != null)
				if (app.getRelativeUri().startsWith("/"))
					uri += app.getRelativeUri();
				else
					uri += "/" + app.getRelativeUri();

		if (module != null)
			if (module.getRelativeUri() != null)
				if (module.getRelativeUri().startsWith("/"))
					uri += module.getRelativeUri();
				else
					uri += "/" + module.getRelativeUri();

		if (resource.getTargetUri() != null)
			if (resource.getTargetUri().startsWith("/"))
				uri += resource.getTargetUri();
			else
				uri += "/" + resource.getTargetUri();

		uri = uri.replace("//", "/");

		RESTConfiguredRestlet cr = new RESTConfiguredRestlet();
		cr.setApplication(app);
		cr.setModule(module);
		cr.setResource(resource);
		server.getApplication().setupResource(contextName, uri, cr);

	}

	public RESTServer getServer() {
		return server;
	}

	public void setServer(RESTServer server) {
		this.server = server;
	}

	public String getContextName() {
		return contextName;
	}

	public void setContextName(String contextName) {
		this.contextName = contextName;
	}

}
